﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace ConcordWinManager
{
    public class User
    {
        //public Consultant consultant;

        public User()
        {
            //this.consultant = new Consultant();
        }

        public int id_user;

        public int id_consultant;

        public string Username;

        public string Password;

        /// <summary>
        /// Имеет права администратора
        /// </summary>
        public bool IsAdminRole;

        /// <summary>
        /// Аккаунт активен
        /// </summary>
        public bool IsAccountLocked;

        /// <summary>
        /// Может удалять контагентов
        /// </summary>
        public bool CanDeleteContragent;

        /// <summary>
        /// Может заключать договора
        /// </summary>
        public bool CanAddContract;

        /// <summary>
        /// Может удалять договора
        /// </summary>
        public bool CanDeleteContract;


        public Boolean Check(string username, string pwd_md5)
        {
            DataSet ds = new DataSet();

            string query = string.Format("SELECT * FROM [dbo].[User] WHERE [Username] = '{0}' AND [Pwd_hash] = '{1}'", 
                username, 
                pwd_md5);

            try
            {
                Tools.RunWithProgressIndicator(null, delegate
                {
                    SqlConnection sql_cn = new SqlConnection(DB.sc_str.ToString());
                    sql_cn.Open();

                    SqlDataAdapter sql_da = new SqlDataAdapter(query, sql_cn);
                    sql_da.Fill(ds, "dbo.User");

                    sql_cn.Close();
                });
            }
            catch (Exception ex)
            {
                return false;
            }         

            if (ds.Tables[0].Rows.Count == 0)
            {
                return false;
            }
            else 
            {
                id_consultant = 0;

                //if (bool.Parse(ds.Tables["dbo.User"].Rows[0]["StatusActive"].ToString()))
                //{
                //    return false;
                //}
                this.id_user = int.Parse(ds.Tables["dbo.User"].Rows[0]["id_user"].ToString());
                this.Username = ds.Tables["dbo.User"].Rows[0]["Username"].ToString();
                this.IsAdminRole = bool.Parse(ds.Tables["dbo.User"].Rows[0]["Admin"].ToString());
                this.IsAccountLocked = bool.Parse(ds.Tables["dbo.User"].Rows[0]["IsAccountLocked"].ToString());
                this.CanAddContract = bool.Parse(ds.Tables["dbo.User"].Rows[0]["CanAddContract"].ToString());
                this.CanDeleteContract = bool.Parse(ds.Tables["dbo.User"].Rows[0]["CanDeleteContract"].ToString());
                this.CanDeleteContragent = bool.Parse(ds.Tables["dbo.User"].Rows[0]["CanDeleteContragent"].ToString());

                if (int.TryParse(ds.Tables["dbo.User"].Rows[0]["id_consultant"].ToString(), out id_consultant))
                {

                }
                else
                {
                    //пользователь есть, консультанта нет
                    return false;
                }

                return true;
            }
                                   
        }

        public void SelectByUsername(string username)
        {            
 
        }

        public Boolean SelectByConsultantId(int id)
        {
            string query = string.Format("SELECT * FROM [dbo].[User] WHERE id_consultant = '{0}'",
               id);

            DataSet ds = new DataSet();

            DB.query_table(query, "dbo.User", ref ds);

            if (ds.Tables[0].Rows.Count == 0)
            {
                return false;
            }
            else
            {
                this.id_user = int.Parse(ds.Tables["dbo.User"].Rows[0]["id_user"].ToString());
                this.Username = ds.Tables["dbo.User"].Rows[0]["Username"].ToString();
                this.IsAdminRole = bool.Parse(ds.Tables["dbo.User"].Rows[0]["Admin"].ToString());
                this.IsAccountLocked = bool.Parse(ds.Tables["dbo.User"].Rows[0]["IsAccountLocked"].ToString());
                this.CanAddContract = bool.Parse(ds.Tables["dbo.User"].Rows[0]["CanAddContract"].ToString());
                this.CanDeleteContract = bool.Parse(ds.Tables["dbo.User"].Rows[0]["CanDeleteContract"].ToString());
                this.CanDeleteContragent = bool.Parse(ds.Tables["dbo.User"].Rows[0]["CanDeleteContragent"].ToString());

                if (int.TryParse(ds.Tables["dbo.User"].Rows[0]["id_consultant"].ToString(), out id_consultant))
                {
                    return true;
                }

                return false;
            }
        }

        public Boolean Exist(string username)
        {
            string query = string.Format("SELECT * FROM [dbo].[User] WHERE [Username] = '{0}'",
                username);

            DataSet ds = new DataSet();

            DB.query_table(query, "dbo.User", ref ds);

            if (ds.Tables[0].Rows.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }

        }

        public void Insert()
        {
            string query = string.Format("INSERT INTO [dbo].[User] " +
               " (Username, Pwd_hash, Admin, id_consultant) " +
               " VALUES ('{0}','{1}', '{2}', {3})",
               this.Username,
               this.Password,
               this.IsAdminRole,
               this.id_consultant
               
               );

            DB.execute_sql(query);
            this.id_user = DB.max_num("[dbo].[User]", "id_user");
        }

        /// <summary>
        /// Обновление информации о пользователе
        /// </summary>
        public void UpdateInfo()
        {
            string query = string.Format("UPDATE [dbo].[User] SET Username='{0}', Pwd_hash='{1}', " +
                " Admin='{2}' WHERE (id_user = '{3}')",
                this.Username,
                this.Password,
                this.IsAdminRole,
                this.id_user
                );

            DataSet ds = new DataSet();

            DB.query_table(query, "[dbo].[User]", ref ds);
        }

        /// <summary>
        /// Обновление прав доступа пользователей
        /// </summary>
        public void UpdateRole()
        {
            string query = string.Format("UPDATE [dbo].[User] SET Admin = '{0}', IsAccountLocked = '{1}', " +
                "CanAddContract = '{2}', CanDeleteContract = '{3}', CanDeleteContragent = '{4}' WHERE (id_user = '{5}')",
                          this.IsAdminRole,
                          this.IsAccountLocked,
                          this.CanAddContract,
                          this.CanDeleteContract,
                          this.CanDeleteContragent,
                          this.id_user
                          );

            DataSet ds = new DataSet();

            DB.query_table(query, "[dbo].[User]", ref ds);
        }
    }
}
